import { login, getUserInfoApi, getUserDetailApi } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    // 用户信息
    userInfo: {}
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
    },
    REMOVE_TOKEN(state) {
      state.token = ''
      removeToken()
    },
    // 设置用户信息
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    async fetchLogin(store, logiinForm) {
      // 调用接口，结构数据，调用mutation设置token，返回数据
      const { data } = await login(logiinForm)
      store.commit('SET_TOKEN', data)
      return data
    },
    // 调用接口，获取用户信息
    async fetchUserInfo(store) {
      const { data } = await getUserInfoApi()
      const res2 = await getUserDetailApi(data.userId)
      store.commit('SET_USERINFO', { ...data, ...res2.data })
    }
  }
}
